(function($){
	/**
	 * format string message
	 * e.g. $.formatMessage('{1} is a good man', 'daniel');
	 */
	$.formatMessage = function(string){
		var args = arguments;
	    var pattern = new RegExp("{([1-" + arguments.length + "])}", "g");
	    return String(string).replace(pattern, function(match, index) {
	       return args[index];
	    });		
	};

	$.createUID = function() {
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
			return v.toString(16);
		});
	}
	
    $.getParameter = function (name) {
        name = name.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
        var regexS = '[\\?&]' + name + '=([^&#]*)';
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.search);
        if (results == null) {
            return '';
        }
        else {
            return decodeURIComponent(results[1].replace(/\+/g, ' '));
        }
    };

    $.getParameters = function (name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS, 'ig');
        var results;
        var ret = [];
        var href = window.location.search;
        while ((results = regex.exec(href))) {
            ret.push(decodeURIComponent(results[1].replace(/\+/g, " ")));
        }
        return ret;
    };
    
	/**
	 * 动态加载JS或CSS文件
	 * @param fileUrl
	 * @param filetype js/css
	 * @param documentObj 默认是window.document对象
	 */
	$.loadJsCssFile = function(fileUrl, filetype, documentObj) {
		var fileref;
		documentObj = documentObj || window.document;
		if(filetype == "js") {
			fileref = documentObj.createElement('script')
			fileref.setAttribute("type", "text/javascript")
			fileref.setAttribute("src", fileUrl)
		} else if(filetype == "css") {
			fileref = documentObj.createElement("link")
			fileref.setAttribute("rel", "stylesheet")
			fileref.setAttribute("type", "text/css")
			fileref.setAttribute("href", fileUrl)
		}
		if(typeof fileref != "undefined")
			documentObj.getElementsByTagName("head")[0].appendChild(fileref)
	}

})(jQuery);

/* -- $.dealPasteImg extension -- */
(function($) {
	/**
	 * 返回截图后存在于粘贴板中的图片数据转成的img对象
	 * @param callbackFunc: 生成图片的回调事件，提供的参数为图片对象callbackFunc(image)
	 * @param windowObj: 注册粘贴事件的window对象,默认为window
	 * 应用场景：当粘贴行为是发生在iframe里面的元素时，需要将iframe.contentWindow作为windowObj参数传进来，iframe必须同域
	 */
	$.dealPasteImg = function(callbackFunc, windowObj) {
		var callback = callbackFunc;
		var clipboardCatcher;
		
		if(!window.Clipboard){  //for firefox
			var doc = windowObj.document;
			clipboardCatcher = doc.createElement("div");
			clipboardCatcher.setAttribute("contenteditable", "");
			doc.body.appendChild(clipboardCatcher);
			clipboardCatcher.focus();
			$(doc).click(function(e) {
				if (!$(e.target).is("input")) {
					clipboardCatcher.focus();
				}
			});
		}		
		
		if (windowObj) {
			windowObj.addEventListener("paste", pasteHandler);			
		} else {
			window.addEventListener("paste", pasteHandler);
		}
		
		/* Handle paste events */
		function pasteHandler(e) {
			// We need to check if event.clipboardData is supported (Chrome)
			if(e.clipboardData) {
				// Get the items from the clipboard
				var items = e.clipboardData.items;
				if(items) {
					// Loop through all items, looking for any kind of image
					for(var i = 0; i < items.length; i++) {
						if(items[i].type.indexOf("image") !== -1) {
							// We need to represent the image as a file,
							var blob = items[i].getAsFile();
							// and use a URL or webkitURL (whichever is available to the browser)
							// to create a temporary URL to the object
							var URLObj = window.URL || window.webkitURL;
							var source = URLObj.createObjectURL(blob);
	
							// The URL can then be used as the source of an image
							createImage(source);
						}
					}
				}
			} else {
				// This is a cheap trick to make sure we read the data
				// AFTER it has been inserted.
				setTimeout(checkInput, 1);
			}
		}
	
		/* Parse the input in the paste catcher element */
		function checkInput() {
			// Store the pasted content in a variable
			var pasteCatcher = clipboardCatcher;
			var child = pasteCatcher.childNodes[0];
	
			// Clear the inner html to make sure we're always
			// getting the latest inserted content
			// pasteCatcher.innerHTML = "";
	
			if(child) {
				// If the user pastes an image, the src attribute
				// will represent the image as a base64 encoded string.
				if(child.tagName === "IMG") {
					createImage(child.src);
				}
			}
		}
	
		/* Creates a new image from a given source */
		function createImage(source) {
			var pastedImage = new Image();
			pastedImage.onload = function() {
				if (typeof(callback) == 'function') {
					callback(pastedImage);
				}
			}
			pastedImage.src = source;
		}		
	}
	
})(jQuery);


/* -- $.upload extension -- */
(function($) {
	
	/**
	 * 上传文件
	 * @required FileReader API
	 * @param uploadUrl: 服务器上传服务URL
	 * @param file: 要上传的文件File/Blob对象
	 * @param data: 参数,格式：{param1:'val1', param2:'val2'}
	 * @param progressCallback: 上传过程中的回调函数，可用于显示上传进度
	 * @param uploadedCallback: 上传成功后的回调函数
	 */
	var data, progressCallback;
	$.upload = function(uploadUrl, file, data, progressCallback, uploadedCallback) {
		data = data;
		var reader = new FileReader();
		reader.onloadend = send;
		reader.readAsBinaryString(file);

		function send(e) {

			var xhr = new XMLHttpRequest(), upload = xhr.upload, start_time = new Date().getTime(), boundary = '------multipartformboundary' + (new Date).getTime(), builder;
			
			if (file.name && file.name.indexOf('.') != -1) { //File Object
				builder = getBuilder(file.name, e.target.result, boundary);
			} else { //Blob Object
				var filename = new Date().getTime() + '.' + file.type.split('/')[1];
				builder = getBuilder(filename, e.target.result, boundary);
			}

			upload.file = file; 
			upload.downloadStartTime = start_time;
			upload.currentStart = start_time;
			upload.currentProgress = 0;
			upload.startData = 0;
			upload.addEventListener("progress", progress, false);

			xhr.open("POST", uploadUrl, true);
			xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);

			xhr.sendAsBinary(builder);

			xhr.onload = function() {
				//TODO 这里需要根据后台实际返回的数据进行判断是否上传成功
				if(xhr.responseText) {
					if (uploadedCallback && typeof(uploadedCallback) == 'function') {
						uploadedCallback(xhr.responseText);
					}
				}
			};
		}
	};

	function progress(e) {
		if(e.lengthComputable) {
			var percentage = Math.round((e.loaded * 100) / e.total);
			if(this.currentProgress != percentage) {

				this.currentProgress = percentage;
				if (progressCallback && typeof(progressCallback) == 'function') {
					progressCallback(this.currentProgress);
				}
			}
		}
	}
	
	function getBuilder(filename, filedata, boundary) {
		var dashdash = '--', crlf = '\r\n', builder = '';

		if (data) {
			$.each(data, function(i, val) {
				if( typeof val === 'function')
					val = val();
				builder += dashdash;
				builder += boundary;
				builder += crlf;
				builder += 'Content-Disposition: form-data; name="' + i + '"';
				builder += crlf;
				builder += crlf;
				builder += val;
				builder += crlf;
			});
		}
		builder += dashdash;
		builder += boundary;
		builder += crlf;
		builder += 'Content-Disposition: form-data; name="userfile"';
		builder += '; filename="' + filename + '"';
		builder += crlf;
		builder += 'Content-Type: application/octet-stream';
		builder += crlf;
		builder += crlf;
		builder += filedata;
		builder += crlf;
		builder += dashdash;
		builder += boundary;
		builder += dashdash;
		builder += crlf;
		return builder;
	};

	try {
		if(XMLHttpRequest.prototype.sendAsBinary)
			return;
		XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
			function byteValue(x) {
				return x.charCodeAt(0) & 0xff;
			}

			var ords = Array.prototype.map.call(datastr, byteValue);
			var ui8a = new Uint8Array(ords);
			this.send(ui8a.buffer);
		}
	} catch(e) {
		console.log(e);
	}


})(jQuery);


(function($) {

	/* 
	 * 将img对象转成Blob对象
	 * @required canvas-to-blob.js (https://github.com/blueimp/JavaScript-Canvas-to-Blob)
	 * @param img img对象
	 * @param imgType 图片类型,默认为jpeg
	 * @param callback 生成blob对象的回调函数，提供的参数为Blob对象callback(BlobObj)
	 */
	$.convertImgToBlob = function(img, imgType, callback) {
	    // Create an empty canvas element
	    var canvas = document.createElement("canvas");
	    canvas.width = img.width;
	    canvas.height = img.height;
	    
	    if (!imgType) imgType = 'jpeg';
	
	    // Copy the image contents to the canvas
	    var ctx = canvas.getContext("2d");
	    ctx.drawImage(img, 0, 0);
	    
		if (canvas.toBlob) {
		    canvas.toBlob(
		        function (blob) {
		           if (callback && typeof(callback) == 'function') {
			           callback(blob);
		           }
		        },
		        'image/'+imgType
		    );
		}			
	}
})(jQuery);
